package com.punch.course.service.impl;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.punch.common.dto.course.ClassRoomDTO;
import com.punch.common.dto.course.ClassRoomImportDTO;
import com.punch.common.dto.user.user.RedisUserDTO;
import com.punch.common.enums.user.role.UserRoleEnum;
import com.punch.common.exception.BusinessException;
import com.punch.common.feign.FeignAreaService;
import com.punch.common.page.PageInfo;
import com.punch.common.redis.utils.UserUtil;
import com.punch.common.tools.BasePage;
import com.punch.common.utils.HulToolExcelUtil;
import com.punch.common.utils.StringUtil;
import com.punch.common.vo.course.ClassRoomPageVO;
import com.punch.common.vo.course.ClassRoomVO;
import com.punch.common.vo.course.SimpleClassRoomVO;
import com.punch.course.exception.CourseExceptionEnum;
import com.punch.course.mapper.ClassRoomMapper;
import com.punch.course.model.PunchClassRoom;
import com.punch.course.query.ClassRoomQueryInfo;
import com.punch.course.service.ClassRoomService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * CourseService-教室信息 服务类
 *
 * @author xiaol
 * @version 1.0.0
 * @since 2020/7/20
 */
@Service
@Slf4j
public class ClassRoomServiceImpl extends ServiceImpl<ClassRoomMapper, PunchClassRoom> implements ClassRoomService {

    @Resource
    private FeignAreaService feignAreaService;

    /**
     * 条件分页查询教室列表
     *
     * @return 教室信息
     */
    @Override
    public PageInfo<ClassRoomPageVO> listClassRoom(ClassRoomQueryInfo queryInfo) {
        RedisUserDTO loginUser = UserUtil.getLoginUser();
        //学校
        if (queryInfo.getCurrentRoleId() == UserRoleEnum.SCHOOL.getCode()) {
            queryInfo.setCreateId(loginUser.getUserId());
        }
        queryInfo.setCurrentRoleId(loginUser.getRoleId());
        queryInfo.setCurrentAreaId(loginUser.getAreaId());
        return BasePage.queryBasePage(queryInfo, params -> this.getBaseMapper().queryCount(params), params -> this.getBaseMapper().queryList(params));
    }

    /**
     * 保存教室信息
     *
     * @param classRoomDTO 教室信息
     * @return 教室记录id
     */
    @Override
    public Long saveClassRoom(ClassRoomDTO classRoomDTO) {
        PunchClassRoom punchClassRoom = new PunchClassRoom();
        //保存教室基本信息
        BeanUtils.copyProperties(classRoomDTO, punchClassRoom);
        RedisUserDTO loginUser = UserUtil.getLoginUser();
        punchClassRoom.setAreaId(loginUser.getAreaId());

        punchClassRoom.setAreaName(loginUser.getAreaName());
        punchClassRoom.setCreateId(loginUser.getUserId());
        Integer currentUserAreaId = loginUser.getAreaId();
        punchClassRoom.setAreaId(currentUserAreaId);
        String parentIds = feignAreaService.getParentIds(currentUserAreaId);
        punchClassRoom.setAllAreaId(parentIds + "," + currentUserAreaId);
        punchClassRoom.setCreateName(loginUser.getUsername());
        if (!save(punchClassRoom)) {
            throw new BusinessException(CourseExceptionEnum.CLASSROOM_SAVE_FAIL);
        }
        return punchClassRoom.getId();
    }


    /**
     * 修改教室信息
     *
     * @param classRoomDTO 教室信息
     * @return 教室记录id
     */
    @Override
    public Long updateClassRoom(ClassRoomDTO classRoomDTO) {
        PunchClassRoom punchClassRoom = new PunchClassRoom();
        //修改教室基本信息
        BeanUtils.copyProperties(classRoomDTO, punchClassRoom);
        //设置ID
        punchClassRoom.setId(classRoomDTO.getClassRoomId());
        if (!updateById(punchClassRoom)) {
            throw new BusinessException(CourseExceptionEnum.CLASSROOM_EDIT_FAIL);
        }
        return punchClassRoom.getId();
    }


    /**
     * 删除教室信息
     *
     * @param classRoomId 教室ID
     */
    @Override
    public void deleteClassRoomById(Long classRoomId) {
        PunchClassRoom punchClassRoom = getById(classRoomId);
        if (null != punchClassRoom) {
            //删除教室信息（软删除）
            removeById(classRoomId);
        } else {
            throw new BusinessException(CourseExceptionEnum.CLASSROOM_DEL_FAIL_NULL);
        }
    }


    /**
     * 查询教室信息详情
     *
     * @param classRoomId 教室记录ID
     * @return ClassRoomVO 教室详情
     */
    @Override
    public ClassRoomVO getClassRoomById(Long classRoomId) {
        PunchClassRoom punchClassRoom = getById(classRoomId);
        if (null != punchClassRoom) {
            ClassRoomVO classRoomVO = new ClassRoomVO();
            BeanUtils.copyProperties(punchClassRoom, classRoomVO);
            return classRoomVO;
        } else {
            throw new BusinessException(CourseExceptionEnum.CLASSROOM_DETAIL_FAIL_NULL);
        }
    }

    /**
     * 教室下拉列表
     *
     * @return List<SimpleClassRoomVO> 教室下拉列表
     */
    @Override
    public List<SimpleClassRoomVO> listClassRoomSimple(String classRoomName, Long classRoomId) {
        Long currentUid = UserUtil.getLoginUser().getUserId();
        if (classRoomId != null && classRoomId.intValue() != 0) {
            //查找该课程的创建者
            currentUid = getById(classRoomId).getCreateId();
        }
        QueryWrapper<PunchClassRoom> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(PunchClassRoom::getCreateId, currentUid);
        List<PunchClassRoom> list = list(queryWrapper);
        List<SimpleClassRoomVO> retList = new ArrayList<>();
        list.forEach(punchClassRoom -> {
            SimpleClassRoomVO simpleClassRoomVO = new SimpleClassRoomVO();
            simpleClassRoomVO.setClassRoomId(punchClassRoom.getId());
            simpleClassRoomVO.setClassRoomName(punchClassRoom.getClassRoomName());
            simpleClassRoomVO.setStuNoMax(punchClassRoom.getClassRoomCapacity());
            retList.add(simpleClassRoomVO);
        });
        return retList;
    }

    /**
     * 教室启用/停用
     *
     * @param classRoomId 教室id
     */
    @Override
    public void enableClassRoom(Long classRoomId) {
        PunchClassRoom classRoomEX = getById(classRoomId);
        if (classRoomEX == null) {
            throw new BusinessException(CourseExceptionEnum.CLASS_ROOM_NOT_EXIST);
        }
        PunchClassRoom updateClassRoom = new PunchClassRoom();
        //启用变成停用

        if (classRoomEX.getEnabled() == 1) {
            updateClassRoom.setEnabled(0);
        }
        //停用变成启用
        if (classRoomEX.getEnabled() == 0) {
            updateClassRoom.setEnabled(1);
        }
        updateClassRoom.setId(classRoomId);
        updateById(updateClassRoom);
    }

    /**
     * 教室导入
     *
     * @param file 文件
     * @return string
     */
    @Override
    public void importClassRoom(MultipartFile file) {
        try {
            ExcelReader reader = ExcelUtil.getReader(file.getInputStream());
            Map<String, String> headerAlias = HulToolExcelUtil.createExcelHeader(ClassRoomImportDTO.class);
            reader.setHeaderAlias(headerAlias);
            List<ClassRoomImportDTO> importStudentList = reader.readAll(ClassRoomImportDTO.class);
            List<PunchClassRoom> insertList = new ArrayList<>();
            RedisUserDTO loginUser = UserUtil.getLoginUser();
            importStudentList.forEach(classRoomImportDTO -> {
                PunchClassRoom punchClassRoom = new PunchClassRoom();
                punchClassRoom.setClassRoomName(StringUtil.replaceBlank(classRoomImportDTO.getClassRoomName()));
                punchClassRoom.setClassRoomCapacity(classRoomImportDTO.getClassRoomCapacity());
                punchClassRoom.setCreateId(loginUser.getUserId());
                punchClassRoom.setCreateName(loginUser.getUsername());
                punchClassRoom.setAreaId(loginUser.getAreaId());
                punchClassRoom.setAreaName(loginUser.getAreaName());
                insertList.add(punchClassRoom);
            });
            saveBatch(insertList);
        } catch (IOException e) {
            log.error("读取文件错误:{}", e.getMessage());
        }
    }


}





